<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <template id="sub-component">
        <div>
            <p>{{name}}</p>
        </div>
    </template>
    <main id="app">
        <keep-alive>
            <component :is="comName"></component>
        </keep-alive>
        <button @click="comIs = !comIs" >切换</button>
    </main>
</body>
<script src="../vue.js"></script>
<script>
    Vue.component("sub-component1", {
        template: "#sub-component",
        data() {
            return {
                name: "我是组件1"
            }; 
        },
        created() {
            console.log("组件1创建")
        },
        mounted() {
            console.log("组件1挂载")
        },
        activated() {
            console.log("组件1激活")
        },
        deactivated() {
            console.log("组件1失活")
        }
    });

    Vue.component("sub-component2", {
        template: "#sub-component",
        data() {
            return {
                name: "我是组件2"
            }
        }
    });

    new Vue({
        el: "#app",
        data() {
            return {
                comIs: true
            }
        },
        computed: {
            comName() {
                return this.comIs ? "sub-component1" : "sub-component2"
            }
        }
    })
</script>

</html>